package com.token.sysflow.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.token.sql.IntegrateSql;
import com.token.sql.PrepareSql;

import java.sql.ResultSet;

/**
 * @author chenjianxiong 2020/5/7
 */
public abstract class SelectTree {
    protected final PrepareSql prepareSql;
    protected final JSONArray array;
    private boolean checkable;

    /**
     *
     * @param iSql
     */
    public SelectTree(IntegrateSql iSql) {
        array = new JSONArray();
        prepareSql = new PrepareSql(iSql);
        checkable = true;
    }

    /**
     *
     * @return
     */
    public boolean getCheckable(){
        return this.checkable;
    }

    /**
     *
     * @param checkable
     */
    public void setCheckable(boolean checkable){
        this.checkable = checkable;
    }
    /**
     *
     * @return
     * @throws Exception
     */
    public abstract JSONArray readData() throws Exception;

    /**
     *
     * @param rs
     * @param checkable
     * @param selectable
     * @throws Exception
     */
    protected void doWhileToJson(ResultSet rs, boolean checkable, boolean selectable) throws Exception {
        if (rs.next()) {
            JSONObject json;
            do {
                json = new JSONObject();
                json.put("id", rs.getString("id"));
                json.put("pId", rs.getString("pid"));
                json.put("checkable", checkable);
                json.put("selectable", selectable);
                json.put("value", rs.getString("id"));
                json.put("title", rs.getString("name"));
                json.put("key", rs.getString("id"));
                if(checkable && selectable){
                    json.put("isLeaf", true);
                }

                array.add(json);
            } while (rs.next());
        }
        rs.close();
    }

    public void close(){
        prepareSql.close();
    }
}
